<template>
    <div class="eb" ref="chartRef">
        <!-- 用于渲染 ECharts 的容器 -->
    </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onUnmounted } from 'vue'

// 获取 DOM 引用
const chartRef = ref(null)
let myEchart = null // ECharts 实例对象

// 绘制图表函数
const drawChart = () => {
    if (!chartRef.value) return // 确保 DOM 存在
    
    myEchart = echarts.init(chartRef.value) // 初始化实例
    
    const option = {
        title: { text: '数据统计' },
        tooltip: { trigger: 'axis' },
        legend: { data: ['订单', '销售额', '注册人数', '管理员人数'] },
        grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
        toolbox: { feature: { saveAsImage: {} } },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['第一周', '第二周', '第三周', '第四周', '第五周', '第六周', '第七周']
        },
        yAxis: { type: 'value' },
        series: [
            { name: '订单', type: 'line', stack: 'Total', data: [1200, 1320, 1010, 1340, 900, 2300, 2100] },
            { name: '销售额', type: 'line', stack: 'Total', data: [2200, 1820, 1910, 2340, 2900, 3300, 3100] },
            { name: '注册人数', type: 'line', stack: 'Total', data: [1500, 2320, 2010, 1540, 1900, 3300, 4100] },
            { name: '管理员人数', type: 'line', stack: 'Total', data: [3200, 3320, 3010, 3340, 3900, 3300, 3200] }
        ]
    }
    
    myEchart.setOption(option) // 渲染图表
    window.addEventListener('resize', handleResize) // 监听窗口Resize
}

// 窗口Resize处理函数
const handleResize = () => {
    myEchart?.resize() // 调整图表尺寸
}

// 生命周期钩子：挂载后绘制图表
onMounted(() => {
    drawChart()
})

// 生命周期钩子：卸载前移除Resize监听
onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
})

// 确保离开页面时清理实例
onUnmounted(() => {
    if (myEchart) {
        myEchart.dispose() // 销毁实例释放内存
        myEchart = null
    }
})
</script>

<style scoped>
.eb {
    width: 100%;
    height: 490px; 
}
</style>